﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Live;
using System.Threading.Tasks;
using System.Collections.Generic;
using System.IO;

namespace CuteRibs.D3Armory.LiveAsyncExtensions
{
	public static class LiveAuthClientAsyncExtension
	{
		public static Task<LiveLoginResult> LoginAsyncTask(this LiveAuthClient client, IEnumerable<string> scopes)
		{
			var tcs = new TaskCompletionSource<LiveLoginResult>();
			client.LoginCompleted += OnLoginCompleted;
			client.LoginAsync(scopes, new OperationState(tcs, client));
			return tcs.Task;
		}

		private static void OnLoginCompleted(object sender, LoginCompletedEventArgs e)
		{
			var state = e.UserState as OperationState;

			if (state != null)
			{
				state.Client.LoginCompleted -= OnLoginCompleted;

				if (e.Error == null)
				{
					state.TaskCompletionSource.TrySetResult(new LiveLoginResult(e.Status, e.Session));
				}
				else
				{
					state.TaskCompletionSource.TrySetException(e.Error);
				}
			}
		}

		private class OperationState
		{
			public LiveAuthClient Client { get; private set; }
			public TaskCompletionSource<LiveLoginResult> TaskCompletionSource { get; private set; }

			public OperationState(TaskCompletionSource<LiveLoginResult> tcs, LiveAuthClient authClient)
			{
				this.TaskCompletionSource = tcs;
				this.Client = authClient;
			}
		}
	}
}
